<template>
  <CDialog
    class="add-account-dialog"
    title="新增子账户"
    v-model:visible="dialogVisible"
    @confirm="handleConfirm"
    @cancel="dialogVisible = false"
    :loading="loading"
    size="small"
  >
    <el-form ref="formRef" :model="formData" :rules="formRules" label-position="top">
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="排放单位">
            <el-input :value="props.assetDepartment" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="排放单位子账户" prop="accountOrgCode">
            <el-select
              v-model="formData.accountOrgCode"
              placeholder="请选择"
              :suffix-icon="SelectIcon"
              @change="handleChangeAccountOrgCode"
            >
              <el-option
                v-for="item in organizationList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </CDialog>
</template>
<script lang="ts">
export default {
  name: 'AddAccountDialog'
};
</script>
<script lang="ts" setup>
import {
  defineProps,
  withDefaults,
  defineEmits,
  computed,
  ref,
  reactive,
  watch,
  defineComponent,
  h
} from 'vue';
import { CDialog } from '@/components/CDialog';
import { useMessage } from '@/hooks/useMessage';
import { rules as formRules } from './rules';
import { createAssetsSubAccount, getDischargeUnitList } from '@/apis/taa/asset/account';
import { GIcon } from '@/components/GIcon/index';
import { getChildFactoryOrg } from '@/apis/system/organization';

// 下拉图标
const SelectIcon = defineComponent({
  setup() {
    return () => h(GIcon, { type: 'c-xian-xia', style: 'font-size: 16px' });
  }
});

interface AddAccountDialogProps {
  visible: boolean;
  assetNo: string;
  assetDepartment: string;
  orgCode: string;
}
const props = withDefaults(defineProps<AddAccountDialogProps>(), {
  visible: false
});
const emit = defineEmits(['update:visible', 'refresh']);

const { createMessage } = useMessage();

const dialogVisible = computed<boolean>({
  get: () => {
    return props.visible;
  },
  set: val => {
    emit('update:visible', val);
  }
});
watch(
  () => dialogVisible.value,
  visible => {
    if (!visible) {
      // 关闭时清空数据
      handleClear();
    } else {
      // 打开时初始化新数据
      initVisible();
    }
  }
);

const formRef = ref();
const loading = ref(false);

const formData = reactive({
  accountOrgCode: '',
  accountName: ''
});

// eslint-disable-next-line no-undef
const dischargeUnitOptions = ref<LabelValueOptions>([]);
async function getDischargeUnitOptions() {
  try {
    const data = await getDischargeUnitList();
    console.log(data, 'dischargeUnitOptions');
    dischargeUnitOptions.value = data.map(item => {
      return {
        label: item.organizationName,
        value: item.organizationCode
      };
    });
  } catch (error) {
    console.log(error, 'error');
  }
}

// eslint-disable-next-line no-undef
const organizationList = ref<LabelValueOptions>([]);

/**
 * 选择完排放单位
 */
async function handleChangeMasterAccountNo() {
  formData.accountOrgCode = '';
  try {
    const res = await getChildFactoryOrg(props.orgCode);
    organizationList.value = res.map(item => {
      return {
        label: item.orgName,
        value: item.orgCode
      };
    });
  } catch (error) {
    console.log('error', error);
    organizationList.value = [];
  }
}

/**
 * 选择子账户组织
 */
function handleChangeAccountOrgCode() {
  formData.accountName =
    organizationList.value?.find(n => n.value === formData.accountOrgCode)?.label || '';
}

// 提交按钮
function handleConfirm() {
  formRef.value?.validate((valid: boolean) => {
    if (valid) {
      submitTaskReq();
    }
  });
}

// 请求接口
async function submitTaskReq() {
  try {
    loading.value = true;
    const params = {
      ...formData,
      assetMasterAccountNo: props.assetNo
    };
    await createAssetsSubAccount(params);
    createMessage.success('新增子账户成功！');
    dialogVisible.value = false;
    loading.value = false;
    emit('refresh');
  } catch (error) {
    loading.value = false;
  }
}

// 关闭时清空数据
function handleClear() {
  loading.value = false;
  formRef.value?.resetFields();
}

// 打开时初始化
async function initVisible() {
  // 获取工厂下拉选项
  getDischargeUnitOptions();
  handleChangeMasterAccountNo();
  handleClear();
}
</script>
